package com.children.growth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.children.growth.entity.Drawing;
import com.children.growth.mapper.DrawingMapper;
import com.children.growth.service.DrawingService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 绘画服务实现类
 * 
 * @author children
 * @since 1.0.0
 */
 @Service
public class DrawingServiceImpl extends ServiceImpl<DrawingMapper, Drawing> implements DrawingService {

    @Value("${file.upload.path:uploads}")
    private String uploadPath;

    @Override
    public boolean createDrawing(Drawing drawing, MultipartFile imageFile) {
        try {
            // 创建上传目录
            String uploadDir = uploadPath + "/drawings/";
            File uploadDirFile = new File(uploadDir);
            if (!uploadDirFile.exists()) {
                boolean created = uploadDirFile.mkdirs();
                if (!created) {
                    System.err.println("无法创建上传目录: " + uploadDir);
                    return false;
                }
            }
            
            // 保存图片文件
            String fileName = UUID.randomUUID().toString() + ".png";
            String filePath = uploadDir + fileName;
            File destFile = new File(filePath);
            
            System.out.println("保存文件到: " + destFile.getAbsolutePath());
            
            // 确保父目录存在
            File parentDir = destFile.getParentFile();
            if (!parentDir.exists()) {
                boolean created = parentDir.mkdirs();
                if (!created) {
                    System.err.println("无法创建父目录: " + parentDir.getAbsolutePath());
                    return false;
                }
            }
            
            // 手动复制文件内容到目标路径
            try (InputStream inputStream = imageFile.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(destFile)) {
                FileCopyUtils.copy(inputStream, outputStream);
            }
            
            // 设置绘画信息 - 使用相对路径用于数据库存储
            drawing.setImagePath("/uploads/drawings/" + fileName);
            drawing.setCreateTime(LocalDateTime.now());
            drawing.setUpdateTime(LocalDateTime.now());
            
            System.out.println("文件保存成功: " + destFile.getAbsolutePath());
            System.out.println("数据库存储路径: " + drawing.getImagePath());
            
            return save(drawing);
        } catch (Exception e) {
            System.err.println("保存绘画文件失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Page<Drawing> getDrawingList(Long userId, Integer pageNum, Integer pageSize) {
        Page<Drawing> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Drawing> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Drawing::getUserId, userId)
               .orderByDesc(Drawing::getCreateTime);
        return page(page, wrapper);
    }

    @Override
    public Drawing getDrawingById(Long id) {
        return getById(id);
    }

    @Override
    public boolean updateDrawing(Drawing drawing) {
        drawing.setUpdateTime(LocalDateTime.now());
        return updateById(drawing);
    }

    @Override
    public boolean deleteDrawing(Long id) {
        Drawing drawing = getById(id);
        if (drawing != null && drawing.getImagePath() != null) {
            // 删除图片文件
            File file = new File(drawing.getImagePath());
            if (file.exists()) {
                file.delete();
            }
        }
        return removeById(id);
    }

    @Override
    public Map<String, Object> analyzeDrawing(Long drawingId) {
        Drawing drawing = getById(drawingId);
        if (drawing == null) {
            return null;
        }

        // 这里应该调用AI服务进行画作分析
        // 暂时返回模拟数据
        Map<String, Object> analysis = new HashMap<>();
        analysis.put("theme", "家庭与爱");
        analysis.put("emotion", "positive");
        analysis.put("colorAnalysis", "使用了温暖的色调，表现出积极的情感");
        analysis.put("suggestion", "孩子通过绘画表达了对家庭的热爱，建议多陪伴孩子");
        analysis.put("tags", new String[]{"家庭", "温暖", "爱"});
        
        return analysis;
    }

    @Override
    public Map<String, Object> getDrawingStatistics(Long userId) {
        LambdaQueryWrapper<Drawing> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Drawing::getUserId, userId);
        
        long totalCount = count(wrapper);
        
        // 统计不同类型的绘画
        long familyCount = count(wrapper.like(Drawing::getTags, "家庭"));
        long natureCount = count(wrapper.like(Drawing::getTags, "自然"));
        long animalCount = count(wrapper.like(Drawing::getTags, "动物"));
        
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalCount", totalCount);
        statistics.put("familyCount", familyCount);
        statistics.put("natureCount", natureCount);
        statistics.put("animalCount", animalCount);
        
        return statistics;
    }
} 